#include "AppConfig.h"
#include <fstream>
#include <iostream>
#include <memory.h>


//获取去除两端空格后的值
std::string CAppConfig::Trim(const std::string& val)
{
	if ("" == val)
	{
		return "";
	}
	char *pszBuf = new char[val.length() + 1];
	const char* pszTmpPtr = val.c_str();
	const char* begPtr = pszTmpPtr;
	const char* endPtr = pszTmpPtr + val.length() - 1;
	while(begPtr < endPtr && ' ' == *begPtr)begPtr++;
	while(begPtr < endPtr && ' ' == *endPtr)endPtr--;
	memcpy(pszBuf, begPtr, endPtr - begPtr + 1);
	pszBuf[endPtr - begPtr + 1] = 0;
	std::string newVal(pszBuf);
	delete[] pszBuf;
	return newVal;
}

bool CAppConfig::LoadConfigFile(const char* pszFileName)
{
	std::ifstream fin(pszFileName);
	if (!fin)
	{
		return false;
	}

	char szBuf[4096] = {0};	
	std::string strGroup("Default");
	while(fin.good())
	{
		memset(szBuf, 0, sizeof(szBuf));
		fin.getline(szBuf,sizeof(szBuf));
		std::string sigLineValue = Trim(szBuf);

		//忽略空行
		if (sigLineValue.size() == 0)
		{
			continue;
		}

		//以#号开头的行表示注释
		if (sigLineValue[0] == '#')
		{
			continue;
		}
		
		if (sigLineValue[0] == '[' && sigLineValue[sigLineValue.size() - 1] == ']')
		{
			strGroup = sigLineValue.substr(1,sigLineValue.size() - 2);
			continue;
		}

		char* pszEqualIdx = strstr(szBuf, "+=");
		if (pszEqualIdx)
		{
			*pszEqualIdx = 0;
			m_paramList[strGroup][Trim(szBuf)] +=  Trim(pszEqualIdx + 2);
			continue;
		}

		pszEqualIdx = strstr(szBuf, "=");
		if (!pszEqualIdx)
		{
			continue;
		}
		
		*pszEqualIdx = 0;

		m_paramList[strGroup][Trim(szBuf)] =  Trim(pszEqualIdx + 1);

	}
	return true;
}

void CAppConfig::AddConfigItem(const std::map<std::string, std::map<std::string, std::string>>& mapConfig)
{
	for (auto iter = mapConfig.begin(); iter != mapConfig.end(); iter++)
	{
		const std::string& strGroup = iter->first;
		const std::map<std::string, std::string>& mapParam = iter->second;
		for (auto it = mapParam.begin(); it != mapParam.end(); it++)
		{
			m_paramList[strGroup][it->first] = it->second;
		}
	}
}

//根据前缀获取值列表
std::vector<std::string> CAppConfig::GetParamByPrefix(const char* pszGroup, const char* pszPrefix)
{
	std::vector<std::string> valList;
	if (m_paramList.find(pszGroup) == m_paramList.end())
	{
		return valList;
	}
	auto &group = m_paramList[pszGroup];
	auto item = group.begin();
	
	for (; item != group.end(); item++)
	{
		int n = item->first.find(pszPrefix);
		if (0 == n)
		{
			valList.push_back(item->second);
		}
	}
	return valList;
}


std::vector<std::string> CAppConfig::GetGroupVec()
{
	std::vector<std::string> groupVec;
	auto item = m_paramList.begin();
	for (; item != m_paramList.end(); item++)
	{
		groupVec.push_back(item->first);
	}
	return groupVec;
}

std::map<std::string, std::string>& CAppConfig::GetGroupMap(const char* pszGroup)
{
	return m_paramList[pszGroup];
}

